package mobileann.mafamily.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.mofind.android.base.L;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class QualityCompressUtil {
    public static Bitmap compressImage(Bitmap image, int size) {
        int option = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, option, baos);
        while (baos.toByteArray().length / 1024 > size) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, option, baos);
            option -= 10;
        }
        image.recycle();
        image = null;
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }
    
    public static ByteArrayOutputStream compressImage2os(Bitmap image, int size) {
        int option = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, option, baos);
        while (baos.toByteArray().length / 1024 > size) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, option, baos);
            option -= 10;
        }
        //
        image.recycle();
        image = null;
        //
        return baos;
    }

    public static void saveBitmap(Bitmap bm, String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            L.e("maf", "error--", e);
        } catch (IOException e) {
            L.e("maf", "error--", e);
        }
        //
        bm.recycle();
        bm = null;
    }
    
    public static void saveBitmap(ByteArrayOutputStream bos, String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            out.write(bos.toByteArray());
            out.flush();
            out.close();         
        } catch (FileNotFoundException e) {
            L.e("maf", "error--", e);
        } catch (IOException e) {
            L.e("maf", "error--", e);
        }
        //
        try {
			bos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			L.e("maf", "error--", e);
		}
    }
}
